package com.xja.ssm.controller;

import com.xja.ssm.entity.Users;
import com.xja.ssm.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("users")
@SessionAttributes({"loginuser"})
public class UserController {

    @Autowired
    private UsersService usersService;

    @RequestMapping("reg")
    public String reg(Users users){
        try {
            usersService.addUser(users);
            return "redirect:/page/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/error.jsp";
    }

    @RequestMapping("login")
    public String login(Model model,Users users){
        try {
            Users loginuser = usersService.selectByName(users.getName());
            if (loginuser==null){
                return "redirect:/page/login.jsp";
            }
            if (!users.getPassword().equals(loginuser.getPassword())){
                return "redirect:/page/login.jsp";
            }
            model.addAttribute("loginuser",loginuser);
            if (loginuser.getIsadmin().equals("true")) {
                return "redirect:/admin/guanli.do";
            }else {
                return "redirect:/house/list.do";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            return "redirect:/error.jsp";
    }

    @RequestMapping("loginout")
    public String loginout(Map map, HttpSession session){
        try {
            session.removeAttribute("loginuser");
            map.clear();
            return "redirect:/page/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
            return "redirect:/error.jsp";
    }
}
